package ysu.sxm.ptjc.Controller;

import com.alibaba.fastjson.JSONArray;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import ysu.sxm.ptjc.Domin.Result;
import ysu.sxm.ptjc.Service.UserService;
import ysu.sxm.ptjc.pojo.UserInfo;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.time.Duration;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/User")
public class UserServlet {


    @Resource
    private RedisTemplate<String,Object>redisTemplate;
    @Resource
    UserService userService;
    ///信息成功为100，失败为104
    //用户登录
    @PostMapping("/login")
    public Result login(@RequestParam String userId, @RequestParam String password){
        UserInfo user=userService.getUserByLogin(userId,password);
        if(user!=null){
            //登陆成功
            String token= UUID.randomUUID()+"";
            //存到redis数据库
            redisTemplate.opsForValue().set(token,user, Duration.ofMinutes(30L));
            return new Result(token,"登陆成功",1);
        }
        return new Result(null,"登陆失败",104);

    }
    //根据token获取信息
    @GetMapping("/getUserOfLogin")
    public Result getUserOfLogin(HttpServletRequest request)throws UnsupportedEncodingException {
        String token=request.getHeader("token");
        Object user=redisTemplate.opsForValue().get(token);

        if(user!=null){
            return new Result(user,"获取用户登录成功",100);
        }
        return new Result(null,"获取登录用户失败",104);
    }

    //增加用户
    @PostMapping("/addUser")
    void add(@RequestBody UserInfo userInfo) throws ParseException {
        userService.save(userInfo);

    }
    //批量删除用户
    @PostMapping("/subUser")
    void deleteByIds(@RequestBody List<Integer>ids) throws ParseException {
        userService.removeByIds(ids);

    }
    //根据权限展示用户信息（老板和管理员）
    @PostMapping("/ShowUser")
    String showUserByPower(String power){
        return JSONArray.toJSONString( userService.showUserByPower(power));
    }
    //修改当前用户信息

    @PostMapping("updateUserInfo")
    void updateUserInfo(UserInfo userInfo){
        userService.updateById(userInfo);
    }
}
